/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arg.deploy.webapp.common;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 *
 * @author utaino
 */
public class FileCreator {

    private static Log LOG = LogFactory.getLog(FileCreator.class);
    public static String newline = System.getProperty("line.separator");

    public static enum DELIMITER {

        PIPE(1, "|"),
        SEMICOLON(2, ";"),
        COMMA(3, ","),
        SPACE(4, " ");
        private Integer id;
        private String value;

        private DELIMITER(Integer id, String value) {
            this.id = id;
            this.value = value;
        }

        public int getId() {
            return id;
        }

        public String getValue() {
            return value;
        }
    }

    public static void createTextOrCsvFile(final OutputStream output, final String delimeterId,
            final String[] columns, final List<String[]> dataList) throws Exception {

        List<String[]> writeDataList = new ArrayList<String[]>();
        if (columns != null && columns.length > 0) {
            writeDataList.add(columns);
        }
        writeDataList.addAll(dataList);
        // write file
        String delimeter = "";
        if (Integer.parseInt(delimeterId) == DELIMITER.PIPE.getId()) {
            delimeter = DELIMITER.PIPE.getValue();
        } else if (Integer.parseInt(delimeterId) == DELIMITER.SEMICOLON.getId()) {
            delimeter = DELIMITER.SEMICOLON.getValue();
        } else if (Integer.parseInt(delimeterId) == DELIMITER.COMMA.getId()) {
            delimeter = DELIMITER.COMMA.getValue();
        } else if (Integer.parseInt(delimeterId) == DELIMITER.SPACE.getId()) {
            delimeter = DELIMITER.SPACE.getValue();
        }
        createTextFile(output, delimeter, writeDataList);
    }

    public static void createFixedWidthTextFile(final OutputStream output,
            final int[] columnLength, final List<String[]> dataList) throws Exception {

        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(output, "UTF-8");
            bw = new BufferedWriter(osw);
            for (String[] datas : dataList) {
                for (int i = 0; i < datas.length; i++) {
                    bw.write(padString(datas[i], columnLength[i]));
                }
                bw.write("\r\n");
//                bw.newLine();
            }
            bw.flush();
            osw.flush();
        } catch (IOException ex) {
            LOG.error("IedFileCreator Error :", ex);
            throw ex;
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    }

    public static void createFixedWidthPadZeroTextFile(final OutputStream output,
            final int[] columnLength, final String[] columnName, final List<String[]> dataList) throws Exception {

        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(output, "UTF-8");
            bw = new BufferedWriter(osw);

            for (String[] datas : dataList) {
                for (int i = 0; i < datas.length; i++) {
                    if (columnName[i].equalsIgnoreCase("SETTLE") || columnName[i].equalsIgnoreCase("LOAN")
                            || columnName[i].equalsIgnoreCase("INPUT") || columnName[i].equalsIgnoreCase("INSUR")
                            || columnName[i].equalsIgnoreCase("DEP") || columnName[i].equalsIgnoreCase("TOTAL")
                            || columnName[i].equalsIgnoreCase("SETLE")) {
                        datas[i] = datas[i].replaceAll("\\.", "").trim();
                        bw.write(padZero(datas[i], columnLength[i]));
                    } else {
                        bw.write(padString(datas[i], columnLength[i]));
                    }
                }

                bw.write("\r\n");
//                bw.newLine();
            }
            bw.flush();
            osw.flush();
        } catch (IOException ex) {
            LOG.error("IedFileCreator Error :", ex);
            throw ex;
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    }

    private static void createTextFile(final OutputStream output, final String delimeter,
            final List<String[]> dataList)
            throws Exception {

        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(output, "UTF-8");
            bw = new BufferedWriter(osw);
            for (String[] datas : dataList) {
                for (int i = 0; i < datas.length - 1; i++) {
                    bw.write(datas[i]);
                    bw.write(delimeter);
                }
                bw.write(datas[datas.length - 1]);
                bw.write("\r\n");

//                bw.newLine();
            }
            bw.flush();
            osw.flush();
        } catch (IOException ex) {
            LOG.error("IedFileCreator Error :", ex);
            throw ex;
        } finally {
            if (bw != null) {
                bw.close();
            }
        }
    }

    public static void createPdfFile(final String fontPath, final OutputStream output, final String[] columns,
            final List<String[]> dataList) throws Exception {

        BaseFont bfComic = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font = new Font(bfComic, 14);

        Document document = new Document();
        // document.setPageSize(PageSize.A4.rotate());
        document.setPageSize(PageSize.A3.rotate());
        document.newPage();

        PdfWriter writer = PdfWriter.getInstance(document, output);
        document.open();
        PdfPTable table = new PdfPTable(columns.length);

        // table.setLockedWidth(false);
        table.setTotalWidth(100);


        // add column
        for (String columnName : columns) {
            PdfPCell col = new PdfPCell(new Phrase(columnName, font));
            //col.setNoWrap(true);
            col.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(col);
        }
        table.setHeaderRows(1);
        // add row
        for (String[] rows : dataList) {
            for (String row : rows) {

                PdfPCell rowData = new PdfPCell(new Phrase(row, font));
                //rowData.setNoWrap(true);
                rowData.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(rowData);
            }
        }

        document.add(table);
        document.close();
        output.flush();
    }

    public static void createExcelFile(final OutputStream output, final String[] columns,
            final List<String[]> dataList) throws Exception {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Export Data");
        // create header
        if (columns != null && columns.length > 0) {
            Row header = sheet.createRow(0);
            int colIdx = 0;
            for (String colName : columns) {
                Cell colCell = header.createCell(colIdx);
                colCell.setCellValue(colName);
                colIdx++;
            }
        }

        // create data row
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                String[] datas = dataList.get(i);
                Row dataRow = sheet.createRow(i + 1);
                if (datas != null && datas.length > 0) {
                    for (int ii = 0; ii < datas.length; ii++) {
                        Cell dataCell = dataRow.createCell(ii);
                        dataCell.setCellValue(datas[ii]);
                    }
                }
            }
        }

        // write excel file
        workbook.write(output);
        output.flush();
    }

    private static String padString(String str, int len) {
        for (int i = str.length(); i < len; i++) {
            str += " ";
        }
        return str;
    }

    private static String padZero(String str, int len) {
        for (int i = str.length(); i < len; i++) {
            str = "0" + str;
        }
        return str;
    }
}
